/*  ------------------------------------------------------------------------
	 NQ Common Services Library
	 
	 Homepage: http://www.awzhome.de/
	 ------------------------------------------------------------------------
	 
	 The contents of this file are subject to the Mozilla Public License
	 Version 1.1 (the "License"); you may not use this file except in
	 compliance with the License. You may obtain a copy of the License at
	 http://www.mozilla.org/MPL/
	 
	 Software distributed under the License is distributed on an "AS IS"
	 basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
	 License for the specific language governing rights and limitations
	 under the License.
	
	 The Original Code is code of NQ Common Services Library.

	 The Initial Developer of the Original Code is Andreas Weizel.
	 Portions created by the Initial Developer are
	 Copyright (C) 2006-2011 Andreas Weizel. All Rights Reserved.
	 
	 Contributor(s): (none)
	 
	 Alternatively, the contents of this file may be used under the terms
	 of the GNU General Public License Version 2.0 or later (the "GPL"),
	 or the GNU Lesser General Public License Version 2.1 or later (the
	 "LGPL"), in which case the provisions of the GPL or the LGPL are
	 applicable instead of those above. If you wish to allow use of your
	 version of this file only under the terms of the GPL or the LGPL and
	 not to allow others to use your version of this file under the MPL,
	 indicate your decision by deleting the provisions above and replace
	 them with the notice and other provisions required by the GPL or the
	 LGPL. If you do not delete the provisions above, a recipient may use
	 your version of this file under the terms of any of the MPL, the GPL
	 or the LGPL.
	 ------------------------------------------------------------------------
*/

using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using AWZhome.NQ.Core;
using AWZhome.NQ.Core.Fluent;
using AWZhome.NQ.CommonServices.Visual;
using System.Linq;
using System.Windows;

namespace AWZhome.NQ.CommonServices
{

	[NQExportedService(SingleInstance = true)]
	internal class ContainerManagerService : NQCollectionServiceBase<string, IContainer>, Services.IContainerManagerService
	{
		private IPersistManager _servPersist;

		private object syncObject;
		private LoopWindow loopForm;

		private List<object> registeredWindows = new List<object>();

		public ContainerManagerService()
		{
			syncObject = NQServiceManager.Instance.SyncObject;

			// Register handler for service creation
			NQServiceManager.Instance.ServiceCreated += NQServiceManager_ServiceCreated;
			NQServiceManager.Instance.AppExitRequested += NQServiceManager_AppExitRequested;
		}

		~ContainerManagerService()
		{
			// Some memory cleaning
			loopForm = null;
			this.ServiceCollection.Clear();
			registeredWindows.Clear();
			registeredWindows = null;
		}

		#region INQContainerManagerService Members

		public string MainContainerName
		{
			get
			{
				return _servPersist.GetSetting("NQCS", "mainContainerName", true).AsString("Main");
			}
		}

		public Type MainContainerService
		{
			get
			{
				ConfigData mainContainerService = _servPersist.GetSetting("NQCS", "mainContainerService", true);
				if (mainContainerService != null)
				{
					Type mainContServiceInterface = Type.GetType(mainContainerService.AsString());
					if (mainContServiceInterface != null)
					{
						return mainContServiceInterface;
					}
					else
					{
						return null;
					}
				}
				else
				{
					return typeof(Services.IMainContainerService);
				}
			}
		}

		public IContainer CreateContainer(string containerName)
		{
			// Use default container service
			return this.CreateContainer(typeof(Services.IMainContainerService), containerName);
		}

		public IContainer CreateContainer(Type containerService, string containerName)
		{
			// Check if we already have that container on screen
			if (this.ServiceCollection.ContainsKey(containerName))
			{
				// Return the open container
				return this.ServiceCollection[containerName];
			}
			else
			{
				// We have to initialize the container first
				IContainer newContainer = ServiceCore
					.Create<IContainer>()
					.UsingType(containerService)
					.To;
				newContainer.Initialize(containerName);
				newContainer.FocusWindow();
				return newContainer;
			}
		}

		public void ShowView(IContainer currentContainer, IView view)
		{
			IContainer targetContainer = currentContainer;

			// If no container is set, create the default container
			if (targetContainer == null)
			{
				targetContainer = this.CreateContainer(this.MainContainerName);
			}

			// Search for a protocol binding
			foreach (string container in _servPersist.GetContainerList())
			{
				ConfigData containerProtocolSetting =
					_servPersist.GetContainerSetting(container, "containerProtocol");
				if (containerProtocolSetting != null)
				{
					if (containerProtocolSetting.AsString() == view.Session.Protocol)
					{
						targetContainer = this.CreateContainer(container);
					}
				}
			}

			// Search for a view binding
			foreach (string container in _servPersist.GetContainerList())
			{
				IList<ConfigData> boundViewsSetting =
					_servPersist.GetContainerListSetting(container, "boundViews");
				if (boundViewsSetting != null)
				{
					for (int i = 0; i < boundViewsSetting.Count; i++)
					{
						if (boundViewsSetting[i].AsString() == view.Name)
						{
							targetContainer = this.CreateContainer(container);
						}
					}
				}
			}

			// If we have a target container, add the view to it
			if ((targetContainer != null) && (targetContainer.ViewManager != null))
			{
				targetContainer.ViewManager.AddView(view, true);
			}
		}

		public string GenerateViewName(IView view)
		{
			IContainerManager containerMan = ServiceCore
				.Get<Services.IContainerManagerService>()
				.To;
			string viewName = NQServiceManager.Instance.GetServiceInfoFromObject(view).ServiceInterface.FullName + "|"
					+ ((view.Session != null) ? view.Session.Protocol : "") + "|" + view.Context;
			int counter = 1;
			bool namefound = false;
			while (true)
			{
				namefound = false;
				// Search for the view name in all open view managers
				foreach (IContainer container in containerMan)
				{
					if (container.ViewManager != null)
					{
						if (container.ViewManager[viewName] != null)
						{
							namefound = true;
							break;
						}
					}
				}
				if (namefound)
				{
					viewName = viewName + "|" + counter;
					counter++;
				}
				else
				{
					break;
				}
			}

			return viewName;
		}

		public void RegisterGUIWindow(object windowObject)
		{
			lock (syncObject)
			{
				if (!registeredWindows.Contains(windowObject))
				{
					// Object hasn't been registered yet, so add it to list
					registeredWindows.Add(windowObject);
				}
			}
		}

		public void UnregisterGUIWindow(object windowObject)
		{
			lock (syncObject)
			{
				if (registeredWindows.Contains(windowObject))
				{
					// Remove registered object from list
					registeredWindows.Remove(windowObject);

					// Exit message loop if there aren't any objects left
					if (registeredWindows.Count == 0)
					{
						loopForm.Close();
					}
				}
			}
		}

		public void EnterMessageLoop()
		{
			// Start the application message loop with internal form
			Application app = new Application();
			loopForm = new LoopWindow(this);
			app.Run(loopForm);
		}

		public void EndGUIApplication()
		{
			// Exit message loop
			loopForm.Close();
		}

		#endregion

		#region Event handlers

		private void NQServiceManager_AppExitRequested(object sender, NQCancelEventArgs e)
		{
			// A GUI application should not be cancelled by the Service Manager
			e.Cancel = true;
			this.EndGUIApplication();
		}

		private void NQServiceManager_ServiceCreated(object sender, NQServiceCreatedEventArgs e)
		{
			IContainer containerTemp = e.CreatedService as IContainer;
			if (containerTemp != null)
			{
				// Handle container initialization
				containerTemp.ContainerOpened += new EventHandler(containerTemp_ContainerOpened);
			}
		}

		private void containerTemp_ContainerOpened(object sender, EventArgs e)
		{
			IContainer containerTemp = sender as IContainer;
			if (containerTemp != null)
			{
				containerTemp.ContainerOpened -= new EventHandler(containerTemp_ContainerOpened);

				// A container has been created, save the instance in internal list
				this.ServiceCollection.Add(containerTemp.Name, containerTemp);

				// We want to be notified, when container gets closed by user
				containerTemp.ContainerClosed += new EventHandler(containerTemp_ContainerClosed);

				// Increment window counter
				RegisterGUIWindow(containerTemp);
			}
		}

		private void containerTemp_ContainerClosed(object sender, EventArgs e)
		{
			// Container has been closed, so remove it from internal list
			IContainer containerTemp = (IContainer) sender;
			if (this.ServiceCollection.ContainsKey(containerTemp.Name))
			{
				containerTemp.ContainerClosed -= new EventHandler(containerTemp_ContainerClosed);
				this.ServiceCollection.Remove(containerTemp.Name);

				// Decrement window counter
				UnregisterGUIWindow(containerTemp);
			}
		}

		#endregion

		internal void PostInitializeManager()
		{
			// Get PersistService instance
			_servPersist = ServiceCore
				.Get<Services.IPersistService>()
				.To;

			// Create main container of default service
			this.CreateContainer(this.MainContainerName);
		}
	}
}
